<template>
  <el-container id="container" style="position: absolute;overflow: hidden;">
    <el-header style="height: 38px;">
      <tool-bar v-if="context" ref="childToolbar" :context="context" :tools="tools" />
      <div class="report-tilte">报表名称：{{ reportFullName }}</div>
    </el-header>
    <el-container style="overflow: hidden;">
      <el-aside width="250px">
        <data-set :data-set-value="dataSetValue" :refresh-child-property-panel="refreshChildPropertyPanel" />
      </el-aside>
      <el-main style="position: relative;">
        <div style="display: flex;height: 24px;background: #f2f4f7;">
          <div style="width: 164px;padding:0px 16px;">
            <div style="border-right: 1px solid #e6e6e6;border-left: 1px solid #e6e6e6;width: 120px;text-align: center;margin-right: 10px;float: left;font-size: 12px;line-height: 24px;height: 24px;background: #fff;">{{ cellName }}</div>
          </div>
          <div style="flex: 1;padding: 0px 15px;">
            <div style="border-right: 1px solid #e6e6e6;border-left: 1px solid #e6e6e6;width: 100%;height: 24px;background: #fff;" />
          </div>
        </div>
        <div id="designer" style="font-size: 13px;" />
        <hr title="打印线" style="width:0px;border-left:dashed 1px #409eff;position: absolute;left: 300pt;top: 30px;z-index: 10" />
      </el-main>
      <el-aside width="400px">
        <property-panel v-if="context" ref="childPropertyPanel" :context="context" />
      </el-aside>
    </el-container>
  </el-container>
</template>

<script>
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/lint/lint.css'

import 'handsontable/dist/handsontable.css'
import Context from './components/Context.js'
import ReportTable from './components/table/ReportTable.js'
import PropertyPanel from './components/panel/PropertyPanel'

import DataSet from './components/dataset'
import { undoManager } from './components/Utils.js'
import PrintLine from './components/PrintLine.js'
import { renderRowHeader } from './components/table/HeaderUtils.js'

import ToolBar from './components/tools/ToolBar'

const elementResizeDetectorMaker = require('element-resize-detector')
// 监听元素变化
const erd = elementResizeDetectorMaker()

export default {
  name: 'Table',
  components: {
    ToolBar,
    PropertyPanel,
    DataSet
  },
  data: function() {
    return {
      cellName: '',
      reportFullName: '未命名',
      extend: false,
      activeName: 'first',
      context: null,
      tools: [],
      dataSetValue: {}
    }
  },
  mounted: function() {
    this.init()
  },
  methods: {
    init: function() {
      const elementId = 'designer'
      const ele = document.getElementById(elementId)
      const that = this
      erd.listenTo(document.querySelector('.el-scrollbar'), function(element) {
        that.$nextTick(function() {
          setTimeout(function() {
            if (that.context && that.context.hot) {
              const height = that.getHeight(ele)
              that.context.hot.updateSettings({
                height: height
              })
              that.context.printLine.refresh()
            }
          }, 210)
        })
      })
      undoManager.setLimit(100)
      const _this = this
      const height = this.getHeight(ele)
      new ReportTable(ele, height, function() {
        _this.context = new Context(this)
        _this.context.elementId = elementId
        const reportFullName = _this.context.reportDef.reportFullName
        if (reportFullName === 'classpath:templates/template.ureport.xml') {
          _this.reportFullName = '未命名'
        } else {
          const prefix = 'file:'
          _this.reportFullName = reportFullName.substring(prefix.length, reportFullName.length)
        }
        this.bindSelectionEvent(function(rowIndex, colIndex, row2Index, col2Index) {
          _this.correctionHandsontableInputHolder(ele, rowIndex, colIndex)
          _this.cellName = _this.context.getCellName(rowIndex, colIndex)
          _this.$refs.childPropertyPanel.refresh(rowIndex, colIndex, row2Index, col2Index)
          _this.$refs.childToolbar.refresh(rowIndex, colIndex, row2Index, col2Index)
        })
        _this.printLine = new PrintLine(_this.context)
        const rows = _this.context.reportDef.rows
        for (const row of rows) {
          const band = row.band
          if (!band) {
            continue
          }
          _this.context.addRowHeader(row.rowNumber - 1, band)
        }
        renderRowHeader(_this.context.hot, _this.context)
        _this.dataSetValue = {
          context: _this.context
        }
      })
      const sheetDiv = document.getElementById('container')
      document.ondragstart = function(ev) {
        ev.dataTransfer.setData('dataset', ev.target.attributes.dataset.nodeValue)
        ev.dataTransfer.setData('field', ev.target.textContent)
      }
      sheetDiv.ondragover = function(ev) {
        console.log('拖拽开始=====')
        ev.preventDefault()
      }
      sheetDiv.ondrop = function(ev) {
        const path = ev.path
        if (!path || path.length === 0) {
          return false
        }
        const ele = path[0]
        if (ele.nodeName.toLowerCase() !== 'td') {
          return false
        }
        const cellIndex = ele.cellIndex
        const tbody_tr = ele.parentNode
        const thead_tr = tbody_tr.parentNode.previousElementSibling.children[0]
        const letter = thead_tr.children[cellIndex].textContent

        const colIndex = letter.charCodeAt(0) - 65
        const rowIndex = tbody_tr.rowIndex - 1

        let cellDef = _this.context.getCell(rowIndex, colIndex)

        // const oldCellDef = Object.assign({}, cellDef)

        const dataset = ev.dataTransfer.getData('dataset').trim()
        const field = ev.dataTransfer.getData('field').trim()

        if (cellDef.value.type !== 'dataset') {
          _this.context.removeCell(cellDef)
          cellDef = {
            value: {
              type: 'dataset',
              conditions: []
            },
            rowNumber: cellDef.rowNumber,
            columnNumber: cellDef.columnNumber,
            cellStyle: cellDef.cellStyle
          }
          _this.context.addCell(cellDef)
        }
        cellDef.expand = 'Down'
        const value = cellDef.value
        value.aggregate = 'group'
        value.datasetName = dataset
        value.property = field
        value.order = 'none'

        let text = value.datasetName + '.' + value.aggregate + '('
        const prop = value.property
        text += prop + ')'
        _this.context.hot.setDataAtCell(rowIndex, colIndex, text)
        console.log('拖拽结束=====')
        ev.preventDefault()
        const selected = _this.context.hot.getSelected()
        if (!selected) {
          return null
        }
        const startRow = selected[0]
        const startCol = selected[1]
        const endRow = selected[2]
        const endCol = selected[3]
        _this.refreshChildPropertyPanel(startRow, startCol, endRow, endCol)
      }
    },
    refreshChildPropertyPanel(rowIndex, colIndex, row2Index, col2Index) {
      this.$refs.childPropertyPanel.refresh(rowIndex, colIndex, row2Index, col2Index)
    },
    getHeight(ele) {
      const height = document.documentElement.clientHeight
      const top = ele.getBoundingClientRect().top
      return height - top
    },
    correctionHandsontableInputHolder(ele, rowIndex, colIndex) {
      const targets = ele.querySelectorAll('.handsontableInputHolder')
      const target = targets[targets.length - 1]
      target.style.marginTop = '0px'
      if (rowIndex > 0) {
        target.style.marginTop = '1px'
      }
      target.style.marginLeft = '0px'
      if (colIndex > 0) {
        target.style.marginLeft = '1px'
      }
    }
  }
}
</script>

<style>
  body {
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
  }

  div.cell {
    -webkit-user-select:text;
    -moz-user-select:text;
    -ms-user-select:text;
    user-select:text;
  }

  img {
    vertical-align: middle;
    border: 0;
  }

  .tool-top-btn {
    margin-top: 10px;
    font-size: 12px;
    margin-left: 20px;
  }

  .dataset-item {
    display: none
  }

  .el-tree-node__content:hover .dataset-item {
    display: inline-block;
  }

  .handsontable tr,.handsontable td,.handsontable th {
    background: transparent;
  }

  .handsontable table.htCore {
    border-collapse: collapse
  }

  .handsontable th {
    border-color: #eeeff1 !important;
    background: #f4f5f8;
    border-bottom: 1px solid #eeeff1;
    color: #909399;
  }

  .handsontable tr:first-child th,
  .handsontable tr:first-child td {
    border-top: 1px solid #e6e6e6;
  }

  .handsontable th, .handsontable td {
    border-top: 1px solid #e6e6e6;
    border-left: 1px solid #e6e6e6;
    border-right: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
  }

  .handsontable tbody th.ht__highlight,
  .handsontable thead th.ht__highlight {
    background-color: #e7edf9;
  }

  .handsontable .wtBorder.current.corner {
    width: 4px !important;
    height: 4px !important;
  }

  .handsontable .wtBorder.area.corner {
    width: 4px !important;
    height: 4px !important;
  }

  .htBorders div.wtBorder.area:nth-child(2),
  .htBorders div.wtBorder.area:nth-child(3),
  .htBorders div.wtBorder.area:nth-child(5),
  .htBorders div.wtBorder.current:nth-child(3),
  .htBorders div.wtBorder.current:nth-child(5){
    margin-top: 1px;
  }

  .handsontable.ht_clone_top table.htCore,
  .handsontable.ht_master table.htCore,
  .htBorders div.wtBorder.area,
  .htBorders div.wtBorder.current{
    margin-left: 1px;
  }

  .htBorders div.wtBorder.area:nth-child(1),
  .htBorders div.wtBorder.area:nth-child(4),
  .htBorders div.wtBorder.area:nth-child(5),
  .htBorders div.wtBorder.current:nth-child(4),
  .htBorders div.wtBorder.current:nth-child(5) {
    margin-left: 2px;
  }

  .htContextMenu table.htCore {
    color: #606266;
    font-size: 14px;
    border: 0px solid #e6e6e6;
    border-bottom-width: 0px;
    border-right-width: 0px;
    background: #fff;
    box-shadow: 1px 2px 5px 2px rgba(51, 51, 51, 0.15);
  }

  .ht_clone_top.handsontable .wtHolder {
    overflow: hidden;
  }

  fieldset {
    padding: 10px;
    border: solid 1px #dddddd;
    border-radius: 3px;
  }

  .condition-dialog fieldset {
    height: 600px;
    width: 170px;
    display: inline-block;
  }

  legend {
    width: auto;
    margin-bottom: 1px;
    border-bottom: none;
    font-size: inherit;
    color: #4b4b4b;
    padding: 0px 5px;
  }

  .condition-dialog .condition-name-block {
    padding: 5px 4px;
    cursor: pointer;
    border-radius: 1px;
  }

  .condition-dialog .condition-name-block-selected {
    background: #409EFF;
    color: #FFFFFF;
  }

  .condition-dialog .condition-name-block:hover {
    background: #F56C6C;
    color: #FFFFFF;
  }

  .CodeMirror-lint-tooltip {
    z-index: 3000;

  }

  .property-row-item {
    height: 28px;
    margin-top: 5px;
  }

  .property-row-item-label {
    line-height: 28px;
  }

  .property-row-item-label.second {
    text-align: center;
  }

  #container {
    margin: 0px;
    padding: 0px;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .sheet-toolbar-btns {
    padding-top: 8px;
    padding-left: 5px;
    color: #606266;
  }

  .sheet-toolbar-btns .el-dropdown {
    color: #606266;
  }

  .sheet-toolbar-btn {
    height: 26px;
    width: 26px;
    cursor: pointer;
    display: inline-block;
    border: 1px solid #dcdfe6;
    border-color: #f9f9f9;
    position: relative;
    border-radius: 2px;
    margin-right: 5px
  }

  .sheet-toolbar-btn:hover,
  .sheet-toolbar-btn.active {
    background: #E4E7ED;
  }

  .sheet-toolbar-btn:hover .sheet-toolbar-dropdown-icon {
    background: #DCDFE6;
  }

  .sheet-toolbar-icon {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    margin: auto;
    height: 17px;
    width: 16px;
  }

  .sheet-toolbar-btn.dropdown {
    margin-right: 15px;
  }

  .sheet-toolbar-dropdown-icon {
    position: absolute;
    height: 24px;
    right: -14px;
    top: 0px;
    padding: 0px 2px;
    border-radius: 1px;
  }

  .sheet-toolbar-icon i {
    position: absolute;
    top: 0px;
  }

  .sheet-toolbar-btn.dropdown .el-dropdown {
    position: absolute;
    right: 0px;
    height: 22px;
  }

  .caret {
    display: inline-block;
    width: 0;
    height: 0;
    margin: 0px 2px;
    border-top: 4px dashed;
    border-top: 4px solid\9;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
  }

  .x-spreadsheet-color-palette-cell {
    width: 20px;
    height: 20px;
    border: 1px solid #FFFFFF;
    cursor: pointer;
  }

  .x-spreadsheet-color-palette-cell:hover {
    border-color: #DCDFE6;
  }
  .div-block-clearance .el-form-item{
    margin-bottom: 10px;
  }
  .report-tilte {
    position: absolute;
    top:14px;
    right:10px;
    color: #606266;
    font-size: 12px;
  }
</style>
